package com.iwords.android;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONObject;

import com.iwords.android.DBHelper.LearningStatus;

import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;

public class ChangeWordLib {
	IWordsApp iWordsApp;
	Activity activity;
	ChangeWordLib(IWordsApp iWordsApp, Activity activity){
		this.iWordsApp = iWordsApp;
		this.activity = activity;
	}
	/**当用户择新的课本时，将课本词汇从系统词汇表，复制一份到用户词汇库
	boolean userSelectedWordLib(Long currentLibId){
		String href = iWordsApp.getResources().getString(R.string.user_select_lib);
		href = href+currentLibId+"&userid="+iWordsApp.getUser().getUserid();
		HttpPost request = new HttpPost(href);
		//System.out.println("ChangeWordLib.userSelectedWordLib()! href = "+href);
		
		try {
			JSONObject jSONObject = ServerAccessor.access(iWordsApp, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if(!success){
				displayMessage(CodeUtils.decode(jSONObject.getString("message")));
				return false;
			}
		}catch(NeedPayException ne){
			Intent intent = new Intent(iWordsApp, com.iwords.android.AlipayActivity.class);
			iWordsApp.startActivity(intent);
		}catch (Exception e) {
			displayMessage(e.getMessage());
			return false;
		}
		return true;
	}
	*/
	
	/**当用户选择了课本，先判断本地是否已经有了这个课本的词库，如果没有，从服务器下载一份，存储到本地数据库中*/
	boolean userSelectedWordLib(Long currentLibId){
		long time = System.currentTimeMillis();
		long userid = iWordsApp.getUser().getUserid();
		DBHelper dbHelper = new DBHelper(activity);
		try{
			//dbHelper.deleteAll();
			DBHelper.UserLibs userLib = dbHelper.getLib(currentLibId, userid);
			if(userLib == null){
				//说明用户本地没有获取过这个课本
				//System.out.println("ChangeWordLib.userSelectedWordLib() userLib = "+userLib);
				//插入课本记录并设置为当前课本
				dbHelper.clearCurrentLib(userid);
				WordLibsManager.WordLib wordLib = new WordLibsManager(iWordsApp, activity).getWordLib(currentLibId);
				DBHelper.UserLibs lib = new DBHelper.UserLibs();
				lib.iscurrent = true;
				lib.libid = currentLibId;
				lib.userid = userid;
				lib.pid = wordLib.pId;
				lib.libname = wordLib.libName;
				//System.out.println("ChangeWordLib.userSelectedWordLib() to be inserted lib.libname="+lib.libname);
				dbHelper.insert(lib);
				userLib = lib;
				//获取课本词汇到本地，将已经认识的单词过滤掉
				int knownCount = downloadWords(currentLibId, dbHelper);
			}else{
				//设置为当前课本
				dbHelper.clearCurrentLib(userid);
				userLib.iscurrent = true;
				dbHelper.update(userLib);
				List<LearningStatus> learningStatusList = dbHelper.getLearningStatus(userid, currentLibId);
				//其中的一些词汇可能已经背会了，过滤一遍
				Set<String> knowns = dbHelper.getUserKnowns(userid);
				int knowCount = 0;
				for(LearningStatus status : learningStatusList){
					if(knowns.contains(status.spelling.trim())){
						status.familiarity = 7;
						dbHelper.update(status);
						knowCount++;
					}
				}
				//System.out.println("ChangeWordLib.userSelectedWordLib() learningStatusList.size() = "+learningStatusList.size());
			}
			//变更了课本，需要清理当前课本的词汇信息
			WordsQueueManager.getInstance().clearCurrentQueue();
		}finally{
			dbHelper.cleanup();
		}
		//System.out.println("ChangeWordLib.userSelectedWordLib() time consumed : "+(System.currentTimeMillis()-time));
		return true;
	}
	
	private int downloadWords(Long currentLibId, DBHelper dbHelper){
		long userid = iWordsApp.getUser().getUserid();
		String href = iWordsApp.getResources().getString(R.string.sys_word_list);
		href = href + currentLibId;
		HttpPost request = new HttpPost(href);
		//System.out.println("---ChangeWordLib.downloadWords()! href = "+ href);
		int knownCount = 0;
		try {
			JSONObject jSONObject = ServerAccessor.access(activity, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (!success) {
				this.displayMessage(CodeUtils.decode(jSONObject.getString("message")));
				return knownCount;
			}
			JSONArray wordsList = JSONUtils.getArray(jSONObject.getJSONObject("defaultValue"));
			//System.out.println("---WordsQueueManager.loadCurrentQueue()! wordsList = " + wordsList.length());
			Set<String> knowns = dbHelper.getUserKnowns(userid);
			for (int i = 0; i < wordsList.length(); i++) {//"wordid","syslibid","meaning","phonetics","spelling","createtime","updatetime"
				JSONObject jsonObject = wordsList.getJSONObject(i);
				DBHelper.LearningStatus status = new DBHelper.LearningStatus();
				status.userid = iWordsApp.getUser().getUserid();
				status.wordid = jsonObject.optLong("wordid");
				status.libid = jsonObject.optLong("syslibid");
				status.spelling = CodeUtils.decode(jsonObject.optString("spelling"));
				status.phonetics = CodeUtils.decode(jsonObject.optString("phonetics"));
				status.meaning = CodeUtils.decode(jsonObject.optString("meaning"));
				status.createTime = new Date(System.currentTimeMillis());
				status.updateTime = new Date(System.currentTimeMillis());
				//根据用户的掌握情况，过滤掉已经记住的单词
				status.familiarity = 0;//初始化的时候是0
				if(knowns.contains(status.spelling.trim())){
					status.familiarity = 7;
					knownCount++;
				}
				dbHelper.insert(status);
			}
		} catch (Exception e) {
			this.displayMessage(e.getMessage());
		}
		return knownCount;
	}
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(iWordsApp, message, Toast.LENGTH_LONG);
		t1.show();
	}

}
